package com.nowcoder.community.service.impl;

import com.nowcoder.community.entity.PageEntity;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.IFollowService;
import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author cjh
 * @date 2023/1/12 - 18:24
 */
@Service
public class FollowServiceImpl implements IFollowService, CommunityConstant {
    @Autowired
    private RedisTemplate template;
    @Autowired
    private UserServiceImpl userService;

    @Override
    public void follow(int userId, int entityType, int entityId) {
//        需要在两个里面添加 因此需要事务
        template.execute(new SessionCallback() {
            @Override
            public Object execute(RedisOperations operations) throws DataAccessException {
                String followeeKey = RedisKeyUtil.getFolloweeKey(userId, entityType);
                String followerKey = RedisKeyUtil.getFollowerKey(entityType, entityId);

                operations.multi();
                operations.opsForZSet().add(followeeKey, entityId, System.currentTimeMillis());
                operations.opsForZSet().add(followerKey, userId, System.currentTimeMillis());

                return operations.exec();
            }
        });
    }

    @Override
    public void unfollow(int userId, int entityType, int entityId) {
        template.execute(new SessionCallback() {
            @Override
            public Object execute(RedisOperations operations) throws DataAccessException {
                String followeeKey = RedisKeyUtil.getFolloweeKey(userId, entityType);
                String followerKey = RedisKeyUtil.getFollowerKey(entityType, entityId);

                operations.multi();
                operations.opsForZSet().remove(followeeKey, entityId);
                operations.opsForZSet().remove(followerKey, userId);

                return operations.exec();
            }
        });
    }

    /**
     * 查询 关注的实体的数量
     *
     * @param userId
     * @param entityType
     * @return
     */
    @Override
    public long findFolloweeCount(int userId, int entityType) {
        String followeeKey = RedisKeyUtil.getFolloweeKey(userId, entityType);
        return template.opsForZSet().zCard(followeeKey);
    }

    /**
     * 查询 实体的粉丝的数量
     *
     * @param entityType
     * @param entityId
     * @return
     */
    @Override
    public long findFollowerCount(int entityType, int entityId) {
        String followerKey = RedisKeyUtil.getFollowerKey(entityType, entityId);
        return template.opsForZSet().zCard(followerKey);
    }

    /**
     * 查询当前用户是否关注了该实体
     *
     * @param userId
     * @param entityType
     * @param entityId
     * @return
     */
    @Override
    public boolean hasFollowed(int userId, int entityType, int entityId) {
        String followeeKey = RedisKeyUtil.getFolloweeKey(userId, entityType);
        return template.opsForZSet().score(followeeKey, entityId) != null;
    }

    /**
     * 查询某用户关注的人
     *
     * @param userId
     * @param pageEntity
     * @return
     */
    @Override
    public List<Map<String, Object>> findFollowees(int userId, PageEntity pageEntity) {
        String followeeKey = RedisKeyUtil.getFolloweeKey(userId, ENTITY_TYPE_User);
//        按倒序的方式
        Set<Integer> targetIds = template.opsForZSet().reverseRange(followeeKey, (pageEntity.getCurrent() - 1) * pageEntity.getSize(),
                (pageEntity.getCurrent()) * pageEntity.getSize() - 1);
        if (targetIds == null) {
            return null;
        }

        List<Map<String, Object>> list = new ArrayList<>();
        for (Integer targetId : targetIds) {
            Map<String, Object> map = new HashMap<>();
            User user = userService.getById(targetId);
            map.put("user", user);
            Double score = template.opsForZSet().score(followeeKey, targetId);
            map.put("followTime", new Date(score.longValue()));
            list.add(map);
        }

        return list;
    }

    /**
     * 查询某用户的粉丝
     *
     * @param userId
     * @param pageEntity
     * @return
     */
    @Override
    public List<Map<String, Object>> findFollowers(int userId, PageEntity pageEntity) {
        String followerKey = RedisKeyUtil.getFollowerKey(ENTITY_TYPE_User, userId);
        Set<Integer> targetIds = template.opsForZSet().reverseRange(followerKey, (pageEntity.getCurrent() - 1) * pageEntity.getSize(),
                (pageEntity.getCurrent()) * pageEntity.getSize() - 1);
        if (targetIds == null) {
            return null;
        }

        List<Map<String, Object>> list = new ArrayList<>();
        for (Integer targetId : targetIds) {
            Map<String, Object> map = new HashMap<>();
            User user = userService.getById(targetId);
            map.put("user", user);
            Double score = template.opsForZSet().score(followerKey, targetId);
            map.put("followTime", new Date(score.longValue()));
            list.add(map);
        }

        return list;
    }


}
